import React, { useEffect, useContext, ReactText, useRef } from 'react';
import { Form, Divider, Select as AntdSelect } from 'antd';

import { useForm } from 'antd/lib/form/Form';
import { InspectorContext } from '../FlowManage';
import {
  FetchDataParam,
  FetchDataResponse,
  FetchRecordResponse,
  PageSelect,
} from 'components/UILibrary/pageSelect';
import { getSmsTempInfo, getSmsTempList } from 'admin/servers/servers';
import { CustomFormItemsHoc } from './CustomFormHoc';

/**
 * 按键组件
 * 示例： AI管理-机器人管理-版本管理-配置话术流程-按钮组件
 */
const KeyComponent: React.FC = () => {
  const [form] = useForm();
  const smsSelectRef = useRef<any>();
  const { selectedData, onInputChange, onRemoveLink, isView } = useContext(InspectorContext);
  const { Input, TextArea, Switch, InputNumber, Radio, RadioGroup, Checkbox, Option } =
    CustomFormItemsHoc({
      disabled: isView,
    });
  const pressArrayOrigin = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, '*', '#'];
  const pressKeyArrayShow = selectedData.pressKeyArray
    .map((item: any) => item.key)
    .filter((item: any) => item !== '未识别');

  useEffect(() => {
    // 需要手动设置form数据, initialValue初始化属性在切换同组件的props数据时不会更新
    console.log('✅form数据-按键组件-selectedData', selectedData);
    form.setFieldsValue(selectedData);

    setTimeout(() => {
      // 表单验证
      form.validateFields();
    }, 0);
  }, [form, selectedData]);

  useEffect(() => {
    if (selectedData.smsTemplateId) {
      // 短信id-回显
      smsSelectRef.current?.setValue(selectedData.smsTemplateId);
    }
  }, [selectedData.smsTemplateId]);

  const handleChange = (value: any[]) => {
    console.log('选择按键***', value);
    const key_arr = [...value, '未识别'].map(item => {
      return {
        key: item,
      };
    });
    onInputChange('pressKeyArray', key_arr, true);
  };

  const changeKeyComponentType = (value: string) => {
    onInputChange('keyFlag', value, true);
    onRemoveLink('from', selectedData.key);
  };
  /**
   * 查找短信模板的dataProvider
   */
  const fetchSmsTempList = (args: FetchDataParam): FetchDataResponse => {
    return new Promise(resolve => {
      getSmsTempList({
        pageNo: args.pageNum,
        pageSize: args.pageSize,
        templateName: args.keywords,
      })
        .then(res => {
          resolve({
            data: res.data?.map(item => {
              return {
                label: item.templateName,
                value: item.templateId,
              };
            }),
            total: res.count as number,
          });
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  };
  /**
   * pageSelect setValue时查记录的函数:根据id
   */
  const fetchSmsTempRecord = (templateId: ReactText): FetchRecordResponse => {
    return new Promise(resolve => {
      getSmsTempInfo(templateId as number)
        .then(res => {
          const item = res.data;
          resolve({
            label: item.templateName,
            value: item.templateId,
            data: item, // 便于onChange判断，有data则回显赋值不用更新数据
          });
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  };
  return (
    <Form layout="vertical" form={form}>
      <Form.Item
        label="按键组件名称"
        name="title"
        rules={[
          {
            required: true,
            whitespace: true,
            max: 10,
            message: '仅支持输入10个以内字符',
          },
        ]}
        getValueFromEvent={event => {
          return event.target.value.replace(/\s+/g, '');
        }}
      >
        <Input
          maxLength={10}
          // onChange={e => {
          //   onInputChange("title", e.target.value, e.type === "blur");
          // }}
          onBlur={(e: { target: { value: any }; type: string }) => {
            onInputChange('title', e.target.value, e.type === 'blur');
          }}
        />
      </Form.Item>
      <Form.Item
        label="话术内容"
        name="script"
        rules={[
          {
            required: true,
            whitespace: true,
            max: 500,
            message: '仅支持输入500个以内字符',
          },
        ]}
        getValueFromEvent={event => {
          return event.target.value.replace(/\s+/g, '');
        }}
      >
        <TextArea
          maxLength={500}
          // onChange={e => {
          //   console.log(e, "话术内容-onChange");
          //   onInputChange("script", e.target.value, e.type === "blur");
          // }}
          onBlur={(e: { target: { value: any }; type: string }) => {
            console.log(e, '话术内容-onBlur');
            onInputChange('script', e.target.value, e.type === 'blur');
          }}
        />
      </Form.Item>
      {/* <Form.Item label="短信设置">
        <Switch
          defaultChecked={selectedData.smsSwitch === 'on'}
          onChange={(status: any) => {
            onInputChange('smsSwitch', status ? 'on' : 'off', true);
            if (!status) {
              // 关闭时，需要清空短信模板id
              onInputChange('smsTemplateId', undefined, true);
            }
          }}
        />
      </Form.Item>
      {selectedData.smsSwitch === 'on' && (
        <Form.Item name="smsTemplateId" rules={[{ required: true, message: '请选择短信模板' }]}>
          <PageSelect
            disabled={isView}
            allowClear
            key="smsSelect"
            ref={smsSelectRef}
            fetchData={fetchSmsTempList}
            placeholder="请选择短信模板"
            fetchRecord={fetchSmsTempRecord}
            onChange={(val, data) => {
              if (!data) {
                console.log('data无值---赋值更新数据', val, data);
                onInputChange('smsTemplateId', val, true);
              }
            }}
          />
        </Form.Item>
      )} */}
      <Divider />
      <Form.Item style={{ marginBottom: 10 }}>
        <RadioGroup
          value={selectedData.keyFlag}
          onChange={(e: any) => changeKeyComponentType(e.target.value)}
        >
          <Radio value={'PressKey'}>按键</Radio>
          <Radio value={'ReceiveNumber'}>收号</Radio>
        </RadioGroup>
      </Form.Item>
      {selectedData.keyFlag === 'PressKey' && (
        <Form.Item>
          <AntdSelect
            disabled={isView}
            mode="multiple"
            showArrow
            placeholder="请勾选需要的按键"
            defaultValue={pressKeyArrayShow}
            onDeselect={(item: string) => {
              onRemoveLink('fromPort', item, selectedData.key);
            }}
            getPopupContainer={(triggerNode: { parentElement: any }) => triggerNode.parentElement}
            onChange={handleChange}
          >
            {pressArrayOrigin.map(item => {
              return (
                <Option key={item} value={item}>
                  {item}
                </Option>
              );
            })}
          </AntdSelect>
        </Form.Item>
      )}
      {selectedData.keyFlag === 'ReceiveNumber' && (
        <Form.Item>
          <Form.Item name="receiveNumberMin" style={{ display: 'inline-block', marginBottom: 0 }}>
            <InputNumber
              min={1}
              max={99999999}
              precision={0}
              placeholder="最小位数"
              style={{ width: 100, marginRight: '0' }}
              onBlur={(e: { target: { value: any } }) => {
                onInputChange('receiveNumberMin', e.target.value, true);
              }}
            />
          </Form.Item>
          <span
            style={{
              display: 'inline-block',
              width: '20px',
              lineHeight: '32px',
              textAlign: 'center',
              color: '#888',
            }}
          >
            —
          </span>
          <Form.Item name="receiveNumberMax" style={{ display: 'inline-block', marginBottom: 0 }}>
            <InputNumber
              min={1}
              max={99999999}
              precision={0}
              placeholder="最大位数"
              style={{ width: 100, marginRight: '0' }}
              onBlur={(e: { target: { value: any } }) => {
                onInputChange('receiveNumberMax', e.target.value, true);
              }}
            />
          </Form.Item>
          <Form.Item name="receiveNumberEnd" valuePropName="checked" style={{ marginBottom: 0 }}>
            <Checkbox
              onChange={(e: { target: { checked: any } }) => {
                onInputChange('receiveNumberEnd', e.target.checked, true);
              }}
            >
              是否按#结束
            </Checkbox>
          </Form.Item>
        </Form.Item>
      )}
      <Form.Item label="重复次数">
        <RadioGroup
          value={selectedData.numberOfAttempts}
          onChange={(e: { target: { value?: any } }) => {
            onInputChange('numberOfAttempts', e.target.value, true);
          }}
        >
          <Radio value={1}>1</Radio>
          <Radio value={2}>2</Radio>
        </RadioGroup>
      </Form.Item>
      <Form.Item label="超时时长" required>
        <Form.Item name="timeout" rules={[{ required: true, message: '请输入超时时长' }]} noStyle>
          <InputNumber
            min={0}
            max={20}
            precision={0}
            className="timeout"
            placeholder="输入0-20数字"
            style={{ width: 200, marginRight: '5px' }}
            // onChange={value => {
            //   onInputChange("timeout", Number(value), false);
            // }}
            onBlur={(e: { target: { value: any } }) => {
              onInputChange('timeout', Number(e.target.value), true);
            }}
          />
        </Form.Item>
        <span>秒</span>
      </Form.Item>
    </Form>
  );
};

export default KeyComponent;
